import pygame
from pygame.sprite import Sprite
import random

class Alien(Sprite):
    '''外形人对象'''
    def __init__(self, ai_game) :
        super().__init__()
        self.setting = ai_game.setting
        self.screen = ai_game.screen

        self.image = pygame.image.load('images/alien.bmp')
        self.rect = self.image.get_rect()

        # 每个外星人初始化在左上角
        self.rect.x = self.rect.width
        self.rect.y = self.rect.height

        # 存储外星人的水平位置
        self.x = float(self.rect.x)
        # 外形人移动方向，1往左增大坐标，-1往右减小坐标
        self.fleet_direction = random.choice((-1,1))

    def update(self):
        '''更新外星飞船位置，并检测碰触到边缘后弹回'''
        screen_rect = self.screen.get_rect()
        if (self.rect.right >= screen_rect.right) or (self.rect.right <= self.rect.width):
            self.fleet_direction *= -1
            self.rect.y += self.setting.alien_drop_speed * self.setting.alien_speed_rate

        self.x += self.setting.alien_speed * self.fleet_direction * self.setting.alien_speed_rate
        self.rect.x = self.x